package rpcHandler

import (
	"context"
	"fmt"
	"gitee.com/zaiqiang231/lovesport-user-service/app/rpc/proto"
	"gitee.com/zaiqiang231/lovesport-user-service/app/store"
	"github.com/pkg/errors"
	"sync"
)

var (
	userPoliciesSever *UserPoliciesSever
	oncePoliciesSever sync.Once
)

type UserPoliciesSever struct {
}

func GetUserPoliciesSever() (*UserPoliciesSever, error) {
	oncePoliciesSever.Do(func() {
		userPoliciesSever = &UserPoliciesSever{}
	})

	if userPoliciesSever == nil {
		return nil, fmt.Errorf("got nil server")
	}

	return userPoliciesSever, nil
}

func (s *UserPoliciesSever) ListPolicies(ctx context.Context, r *proto.ListPoliciesRequest) (*proto.ListPoliciesResponse, error) {
	if r.Page == nil || r.PageSize == nil {
		return nil, errors.New("Parameter error")
	}

	policyList, err := store.GetDataStore().Policy().List(store.PolicyListOptions{
		Page:     int(*r.Page),
		PageSize: int(*r.PageSize),
	}, "")
	if err != nil {
		return nil, err
	}

	items := make([]*proto.PolicyInfo, 0)
	for _, pol := range policyList.List {
		items = append(items, &proto.PolicyInfo{
			Name:         pol.Name,
			UserName:     pol.UserName,
			PolicyShadow: pol.PolicyShadow,
			CreatedAt:    pol.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return &proto.ListPoliciesResponse{
		TotalCount: policyList.Total,
		Items:      items,
	}, nil
}
